/**
* User: Oleksii Savchenko
* Date: 31.01.13
* Time: 11:06
*/
/**
* Provide CRUD operations
* under Item entity
* @param baseUrl - host of your server
* @param serviceUrl - relative url to your service
* @constructor
*/

function  ItemAjaxService(baseUrl, serviceUrl){
    this._baseUrl = baseUrl ? baseUrl : "/" ;
    this._serviceUrl = serviceUrl ? serviceUrl : "api/items";
    this.request = Object.create(ajax);
}


/**
*  Get item by id
*  @param {Number} id
*  @param {Function} callback
*/

ItemAjaxService.prototype.getItemById = function(params, callback){
    var options = {
        url: this._baseUrl + this._serviceUrl,
        data: null
    };

    var stringQuery = _.reduce(params, function(query, val, key){
        query = query ? query + '&' + key + '=' + val : key + '=' + val;
        return query;
    }, stringQuery);
    return this.request.get(options, callback, stringQuery);
};

/**
*  Get items which contains query string in their names
*  @param {String} query
*  @param {Function} callback
*/

ItemAjaxService.prototype.queryItemsByName = function(query,callback){
    var options = {
        url: this._baseUrl + this._serviceUrl,
        data: {
            data: null
        }
    };
    var params = 'query=' + query;
    return this.request.get(options, callback, params);
};

/**
* Create items provided in items array on the server,
* returns array of items ids to callback
* @param {Array} items
* @param {Function} callback
*/

ItemAjaxService.prototype.create = function(items, callback){
    var options = {
        url: this._baseUrl + this._serviceUrl,
        data: items

    };
    return this.request.create(options, callback);
};

/**
* Update items,
* returns updated items id to callback
* @param {Array} items
* @param {Function} callback
*/

ItemAjaxService.prototype.update = function(items, callback){
    var options = {
        url: this._baseUrl + this._serviceUrl,
        data: items.data,
        params: items.params
    };
    var stringQuery = _.reduce(items.params, function(query, val, key){
        query = query ? query + '&' + key + '=' + val : key + '=' + val;
        return query;
    }, stringQuery);
    return this.request.update(options, callback, stringQuery);
};

/**
* Delete items on the server
* @param {Array} ids  - items ids
* @param {Function} callback
*/

ItemAjaxService.prototype.delete= function(ids, callback){
    var options = {
        url: this._baseUrl + this._serviceUrl
    };
    for(var i = 0; i < ids.length; ids++){
        var stringQuery = _.reduce(ids[i], function(query, val, key){
            query = query ? query + '&' + key + '=' + val : key + '=' + val;
            return query;
        }, stringQuery);
        return this.request.remove(options, callback, stringQuery);
    }
};